<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\service\DeviceService;
use think\Db;

/**
 * 设备管理-控制器
 * @author 牧羊人
 * @since: 2023/08/30
 * Class Device
 * @package app\admin\controller
 */
class Device extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2023/08/30
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->service = new DeviceService();
    }

    /* 历史数据 */
    public function history()
    {
        $param = request()->param();

        $list = [];

        // 5分钟数据
        $dataType = $param['search_type'];

        // 关联设备
        $deviceNo = $param['device_no'];

        if(isset($param['datetime']) && !empty($param['datetime'])){
            $sql = "SELECT FROM_UNIXTIME(create_time - MOD(create_time, ?),'%Y-%m-%d %H:%i:%s') AS time_block, 
                ROUND(AVG(bkll), 2) AS avg_bkll,
                ROUND(AVG(wd), 2) AS avg_wd,
                ROUND(AVG(yl), 2) AS avg_yl,
                ROUND(AVG(yali), 2) AS avg_yali,
                ROUND(AVG(tao_value), 2) AS avg_tao_value, 
                ROUND(AVG(temp), 2) AS avg_temp, 
                ROUND(AVG(voltage), 2) AS avg_voltage,
                ROUND(AVG(chanshui), 2) AS avg_chanshui,
                ROUND(AVG(run_speed), 2) AS avg_run_speed,
                ROUND(AVG(pinlv), 2) AS avg_pinlv,
                ROUND(AVG(dianliu), 2) AS avg_dianliu,
                ROUND(AVG(biao_liuya), 2) AS avg_biao_liuya,
                ROUND(AVG(yezhu_high), 2) AS avg_yezhu_high
                FROM think_history_data
                WHERE create_time >= ? and create_time <= ? and device_no = ? 
                GROUP BY time_block";
            $list = Db::query($sql,[$dataType,$param['datetime'][0] * 0.001,$param['datetime'][1] * 0.001,$deviceNo]);
        }else{
            // 快速搜索
            $hours = $param['fast_search'];
            $sql = "SELECT FROM_UNIXTIME(create_time - MOD(create_time, ?),'%Y-%m-%d %H:%i:%s') AS time_block, 
                ROUND(AVG(bkll), 2) AS avg_bkll,
                ROUND(AVG(wd), 2) AS avg_wd,
                ROUND(AVG(yl), 2) AS avg_yl,
                ROUND(AVG(yali), 2) AS avg_yali,
                ROUND(AVG(tao_value), 2) AS avg_tao_value, 
                ROUND(AVG(temp), 2) AS avg_temp, 
                ROUND(AVG(voltage), 2) AS avg_voltage,
                ROUND(AVG(chanshui), 2) AS avg_chanshui,
                ROUND(AVG(run_speed), 2) AS avg_run_speed,
                ROUND(AVG(pinlv), 2) AS avg_pinlv,
                ROUND(AVG(dianliu), 2) AS avg_dianliu,
                ROUND(AVG(biao_liuya), 2) AS avg_biao_liuya,
                ROUND(AVG(yezhu_high), 2) AS avg_yezhu_high
                FROM think_history_data
                WHERE create_time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL ? HOUR)) and device_no = ?
                GROUP BY time_block";
            $list = Db::query($sql,[$dataType,$hours,$deviceNo]);
        }

        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list
        );
        return $this->jsonReturn($message);
    }

    //  最新一条数据
    function latestdata()
    {
        $param = request()->param();
        $deviceNo = $param['device_no'];
        $data = \app\admin\model\HistoryData::where('device_no',$deviceNo)->order('id desc')->find();

        if($data){
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $data
            );
        }else{
            $message = array(
                "msg" => '没有获取到最新数据',
                "code" => 1,
                "data" => $data
            );
        }
        return $this->jsonReturn($message);
    }

    //  最近1小时数据
    function latest_hourdata()
    {
        $param = request()->param();
        $deviceNo = $param['device_no'];
        $data = \app\admin\model\HistoryData::where('device_no',$deviceNo)
            ->where('create_time >= UNIX_TIMESTAMP() - 3600')
            ->select();

        if($data){
            foreach ($data as $k => $v){
                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }

            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $data
            );
        }else{
            $message = array(
                "msg" => '没有获取到最近1小时数据',
                "code" => 1,
                "data" => $data
            );
        }
        return $this->jsonReturn($message);
    }

    function jkUrl(){

        $param = request()->param();

        $deviceId = $param['device_id'];

        $info = \app\admin\model\Devideo::whereRaw("FIND_IN_SET($deviceId, device_ids)")->find();
        $list['info'] = $info;
        $list['url'] = '';

        if($info){
            $list['info'] = $info;
            // 根据appKey和secret获取accessToken
            $res = $this->postCurl(
                'https://open.ys7.com/api/lapp/token/get',
                ['appKey'=>'de10b972dce64d0b9e20b2de34b727ef','appSecret'=>'e772a6159fef2b4391f689282d093d7b']
            );
            $arr = json_decode($res,true);
            if($arr['code'] == 200){
                $accessToken = $arr['data']['accessToken'];
                $list['url'] = "https://open.ys7.com/ezopen/h5/iframe?url=" . $info->monitor_url . "&autoplay=1&audio=1&accessToken=$accessToken";
            }
        }
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list
        );
        return $this->jsonReturn($message);
    }

    function postCurl($url, $post_data, $headers = [])
    {

        // 初始化cURL会话
        $curl = curl_init();
        // 设置cURL选项
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        //设置header头信息
        #curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 300);

        // 关闭SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

        // 执行cURL请求
        $response = curl_exec($curl);
        // 关闭cURL会话
        curl_close($curl);
        return $response;
    }

    public function all(){
        $list = \app\admin\model\Device::where(['mark'=>1])->order('id asc')->select();

        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list
        );
        return $this->jsonReturn($message);
    }
	
                                        	                                                                        
}